package com.dana1.nos.old;

import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;


public class ObjectKey<T extends ServiceObject> implements Comparable<ObjectKey<T>>
{
	private Class<T> serviceObjectClass;
	private TreeMap<String,Comparable<?>> keyValues = new TreeMap<String,Comparable<?>>();
	private WeakReference<T> myObject = null;
	
	public ObjectKey(Class<T> serviceObjectClass, Map<String, Comparable<?>> keyValues)
	{
		super();
		if (!ServiceObject.class.isAssignableFrom(serviceObjectClass))
			throw new IllegalArgumentException("The service object class must implement the ServiceObject interface");
		this.serviceObjectClass = serviceObjectClass;
		this.keyValues = new TreeMap<String,Comparable<?>>(keyValues);
	}
	public Class<T> getServiceObjectClass()
	{
		return serviceObjectClass;
	}

	public T getServiceObject()
	{
		return myObject==null?null:myObject.get();
	}
	public void setServiceObject(T serviceObject)
	{
		myObject = new WeakReference<T>(serviceObject);
	}
	public Map<String, Comparable<?>> getKeyValues()
	{
		return Collections.unmodifiableMap(keyValues);
	}
	
	@Override
	public int hashCode()
	{
		return serviceObjectClass.hashCode()<<24+keyValues.hashCode();
	}
	@SuppressWarnings("unchecked")
	@Override
	public boolean equals(Object obj)
	{
		if (obj==null) 
			return false;
		if (obj.getClass()!=ObjectKey.class)
			return false;
		return serviceObjectClass.equals(((ObjectKey)obj).serviceObjectClass)
			&&keyValues.equals(((ObjectKey)obj).keyValues);
	}
	@SuppressWarnings("unchecked")
	@Override
	public int compareTo(ObjectKey o)
	{
		int x = serviceObjectClass.toString().compareTo(o.getServiceObjectClass().toString());
		if (x==0)
		{
			Iterator<String> keyIter = keyValues.keySet().iterator();
			String key;
			while((x==0)&&keyIter.hasNext())
			{
				key=keyIter.next();
				x = ((Comparable)keyValues.get(key)).compareTo((Comparable)o.keyValues.get(key));
			}
		}
		return x;
	}
	@Override
	public String toString()
	{
		return "ObjectKey(ServiceObjectClass="+serviceObjectClass+",keyValues="+keyValues+")";
	}
	
}
